window.addEventListener('load', function () {

    let tbody = document.querySelector('tbody')
    function init() {
        axios({
            url: '/score/list',
        }).then(res => {
            console.log(res);
            let data = res.data.data

            let htmlSrc = ''
            for (let key in data) {
                // console.log(key);
                htmlSrc += ` 
            <tr data-id="${key}">
                <th scope="row">${key} </th>
                <td> ${data[key].name}</td>
                <td class="score" data-batch="1" >${data[key].score[0]}  </td>
                <td class="score" data-batch="2" >${data[key].score[1]}  </td>
                <td class="score" data-batch="3" >${data[key].score[2]}  </td>
                <td class="score" data-batch="4" >${data[key].score[3]}  </td>
                <td class="score" data-batch="5" >${data[key].score[4]}  </td>
             </tr>`
            }
            tbody.innerHTML = htmlSrc
        })
    }
    init()


    tbody.addEventListener('click', function (e) {
        if (e.target.className == 'score') {
            // console.log(123);
            let td = e.target
            let score = td.innerHTML

            if (!td.querySelector('input')) {
                //插入输入框之前，清楚原本数据
                td.innerHTML = ''

                //添加一个输入框，追加到td
                let input = document.createElement('input')
                td.appendChild(input)
                // 添加样式

                input.style.textAlign = 'center'
                input.style.border = 'none'
                input.style.background = ' transparent '

                //吧原本数据的值赋值给输入框
                input.value = score

                //让输入框选中
                input.select()
                // 创建一个焦点
                // input.addEventListener('blur', function () {
                //     td.innerHTML = score
                // })

                tbody.addEventListener('keyup', function (e) {
                    if (e.key == 'Enter') {
                        // console.log(11);
                        // console.log(td.parentNode.dataset.id, td.dataset.batch, input.value);
                        console.log(e.target);

                        axios({
                            url: '/score/entry',
                            method: 'POST',
                            data: {
                                stu_id: td.parentNode.dataset.id,
                                batch: td.dataset.batch,
                                score: input.value
                            }
                        }).then(res => {
                            // console.log(res);
                            toastr.success(res.data.message)
                            td.innerHTML = ''
                            td.innerHTML = input.value
                            input.remove()
                        })
                    }
                })

            }
        }
    })



})